#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>
#define SERVPORT 3333
#define MESSAGE_SIZE 10240000

int main(int argc,char *argv[]) {
    int sockfd;
    struct hostent* host;
    struct sockaddr_in serv_addr;

    if(argc < 2) {
        fprintf(stderr, "Please enter the server's hostname");
        exit(1);
    }

    if((host = gethostbyname(argv[1])) == NULL) { //转换为hostent
        perror("gethostbyname");
        exit(1);
    }
	
    if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
        perror("创建 client socket 失败");
        exit(1);
    }
		
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(SERVPORT);
    serv_addr.sin_addr = *((struct in_addr *)host->h_addr);
	
    if((connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr))) == -1) {
        perror("connect error");
        exit(1);
    }
	
	// 调用 fcntl 将客户端连接套接字设置为非阻塞
	fcntl(sockfd, F_SETFL, O_NONBLOCK);
	
	// 给服务端发送数据
	char *data; 
	data = malloc(MESSAGE_SIZE + 1); 
	for (int i = 0; i < MESSAGE_SIZE; i++) { 
		data[i] = 'a'; 
	} 
	data[MESSAGE_SIZE] = '\0';

	int n_written = write(sockfd, data, MESSAGE_SIZE + 1);
	printf("send into buffer %ld \n", n_written);
	if (n_written < 0) {
		perror("send failed");
	}
	
	// 5. 关闭 client socket
    close(sockfd);
}
